<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './dept.data';
  import { getorgtree, orgApi } from '../system-api';
  import { useMessage } from '/@/hooks/web/useMessage';
import { OrgAddInput, UpdateOrgInput } from '/@/api_base/models';

  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const { createMessage } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

        updateSchema([
          {
            field: 'id',
            show: unref(isUpdate),
            required: unref(isUpdate),
          },
        ]);

        const treeData = await getorgtree();
        updateSchema({
          field: 'pid',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          let ret: any;
          if (!unref(isUpdate)) {
            const body: OrgAddInput = {
              orgType: 1,
              name: values.name,
              code: values.code,
              sort: values.sort,
              remark: values.remark,
              pid: values.pid,
            };
            ret = (await orgApi.sysOrgAddPost(body)).data;
          } else {
            const upbody: UpdateOrgInput = {
              id: values.id,
              orgType: 1,
              name: values.name,
              code: values.code,
              sort: values.sort,
              remark: values.remark,
              pid: values.pid,
            };
            ret = (await orgApi.sysOrgEditPost(upbody)).data;
          }
          if (ret != null) {
            if (ret.code == 204) {
              closeModal();
              createMessage.success(ret.message);
            } else {
              createMessage.warning(ret.message + ret.message[0].messages);
            }
          } else {
            createMessage.error('未知错误');
          }

          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
